package com.mt.fpb.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mt.fpb.mapper.*;
import com.mt.fpb.model.WxProduct;
import com.mt.fpb.model.WxProductOrder;
import com.mt.fpb.model.vo.CommonResult;
import com.vbao.service.trade.VbaoChargeSystemHandler;
import com.vbao.service.trade.bean.request.QRCodeRefundRequest;
import com.vbao.service.trade.bean.request.TradeRequestXml;
import com.vbao.service.trade.utils.Base64;
import com.vbao.service.trade.utils.TradeCodeEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**提前赎回的接口
 * FileName: RedeemController
 * Author:   wang
 * Date:     2021/8/20 16:16
 */
@RestController
@Slf4j
@RequestMapping("/Redeem")
public class RedeemController {
    @Resource
    private OrderMoneyMapper orderMoneyMapper;
    @Resource
    private RedeemMapper redeemMapper;
    @Resource
    private PayPasswordMapper payPasswordMapper;

    @Autowired
    private WxProductOrderMapper wxProductOrderMapper;
    @Autowired
    private WxProductMapper wxProductMapper;

    //TODO: 2021/9/30
    @GetMapping("/getRedeemAdvance1")
    //订单编号，支付密码
    public CommonResult getRedeemAdvance(String id, String payPass, String employeeId,String productName,String expirationDay) throws ParseException {
        String Password = payPasswordMapper.selectOldPassword(employeeId);
        String pwd = SecureUtil.md5().digestHex(payPass);
        if (pwd.equals(Password)) {
            Float day = (float) 1 / 365;
            DecimalFormat decimalFormat = new DecimalFormat();
            decimalFormat.format(day);
            Date date = new Date();
            Date ed = redeemMapper.selectED(id);
            Long starTime = ed.getTime();
            Long endTime = date.getTime();
            Float num = (float) ((endTime - starTime) / 24 / 60 / 60 / 1000);
            Float p = redeemMapper.selectday(num);
            decimalFormat.format(p);
            Float RedeemAdvance = (redeemMapper.selectPay(id)) * day * p * num + redeemMapper.selectPay(id);
            orderMoneyMapper.updateOrderMoney(RedeemAdvance, id);

            //提前赎回即打钱给客户，打钱的金额为该订单的收益金额*相对应的赎回利率（refundAmount=orderMoney*利率）
            //通过订单id得到当前订单的收益金额
            QueryWrapper<WxProductOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",id);
            WxProductOrder wxProductOrder = wxProductOrderMapper.selectOne(queryWrapper);
            float orderMoney = wxProductOrder.getOrderMoney();
            float payMoney = wxProductOrder.getPayMoney();
            //通过产品名称查询产品的锁定时间
            QueryWrapper<WxProduct> q = new QueryWrapper<>();
            q.eq("product_name",productName);
            WxProduct  wxProduct = wxProductMapper.selectOne(q);
            int lockTime = wxProduct.getLockTime();//得到产品的锁定天数
            int expirationDays = Integer.parseInt(expirationDay);//得到当前产品的到期天数，需要前端传参
            //计算投资时间 = 产品的锁定天数-产品的到期天数
            int d = lockTime-expirationDays;
            System.out.println("投资天数:"+d);
            float refundAmount =0;
            if(d<90){//判断提前赎回的利率
                refundAmount=orderMoney*0.04f+payMoney;
            }else if(d>=90 && d<180 ){
                refundAmount=orderMoney*0.08f+payMoney;
            }else if(d>=180 && d<365){
                refundAmount=orderMoney*0.1f+payMoney;
            }
            BigDecimal b1 = new BigDecimal(refundAmount);
            float refundAmounts = b1.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();//保留两位小数
            System.out.println("refundAmount:"+refundAmount);
            System.out.println("refundAmounts:"+refundAmounts);

            String result = refund(id,refundAmounts,productName);
            redeemMapper.doRedeem(id,date);
            System.out.println("result:"+result);
            if("OK".equals(result)){
                return CommonResult.success("提前赎回成功", refundAmount);
            }else {
                return CommonResult.success("打款失败", RedeemAdvance);
            }

        }
        return CommonResult.fail(500, "支付密码错误");
    }



    /**
     *退款的方法
     * @Author yu
     * @date 2021/9/6 \
     * @Param [id, refundAmount, productName]
     * @return java.lang.String
     **/

    private String refund(String id,float refundAmount,String productName){
        String InputCharset = "UTF-8";
        String customerNo = "202108240002";
        String key = "n7hPATGKB6aQRfmncrCV";
        String goodNo = "ONEQRCODE";
        String requestGateWayRefundPayXmlurl = "http://pay.chinavbao.com/vbaoPay/cust/payService/QRCodeRefund";
        QRCodeRefundRequest qrCodeRefundRequest = new QRCodeRefundRequest();

        qrCodeRefundRequest.setVersion("6.0");
        qrCodeRefundRequest.setSignType("MD5");
        qrCodeRefundRequest.setInputCharset(InputCharset);
        qrCodeRefundRequest.setCustomerNo(customerNo);
        qrCodeRefundRequest.setGoodNo(goodNo);
        //"YMF" + System.nanoTime()
        qrCodeRefundRequest.setOrderNo(String.valueOf(System.nanoTime())); //退款订单号
        System.out.println("退款订单:"+String.valueOf(System.nanoTime()));

        //通过订单id查询支付时间即表中的start_time
        QueryWrapper<WxProductOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        WxProductOrder wxProductOrder = wxProductOrderMapper.selectOne(queryWrapper);
        Date date = wxProductOrder.getStartTime();
        System.out.println("date:"+date);
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMdd");
        String payDate = sdf.format(date);
        System.out.println("payDate:"+payDate);
        qrCodeRefundRequest.setPayDate(payDate); //支付时间，格式YYYYMMDD


        qrCodeRefundRequest.setRefundOrderNo(id); //被退款的订单号，原支付的商户订单号
        qrCodeRefundRequest.setRefundAmount(String.valueOf(refundAmount));  //退款金额，单位元  格式：100.00
        //http://4130y2w273.qicp.vip   http://money.confidant.top
        qrCodeRefundRequest.setNotifyUrl("http://4130y2w273.qicp.vip:9595/getVbao/get");
        qrCodeRefundRequest.setExt1("");
        qrCodeRefundRequest.setExt2(productName);
        VbaoChargeSystemHandler vbaoChargeSystemHandler = new VbaoChargeSystemHandler();
        TradeRequestXml tradeRequestXml = vbaoChargeSystemHandler.creatRequestXml(qrCodeRefundRequest, key, InputCharset, TradeCodeEnum.QRCODE_PAY_REFUND.getCode());
        System.out.println("发送明文报文:" + tradeRequestXml.getOriRequestXml());
        System.out.println("发送密文报文:" + tradeRequestXml.getRequestXml());
        if (tradeRequestXml.getErrMsg() == null) {
            String returnDKPayxml = vbaoChargeSystemHandler.http(requestGateWayRefundPayXmlurl, tradeRequestXml.getRequestXml(), InputCharset);
            System.out.println("返回密文报文" + returnDKPayxml);
            if (null != returnDKPayxml && returnDKPayxml.length() > 0) {
                String returnOriDKPayxml = "";

                try {
                    returnOriDKPayxml = Base64.decode(returnDKPayxml, InputCharset);
                    System.out.println("解密后报文" + returnOriDKPayxml);
                    if (null != returnOriDKPayxml && returnOriDKPayxml.length() > 0) {
                        boolean flag = vbaoChargeSystemHandler.verifySignature(returnOriDKPayxml, key, InputCharset);
                        if (flag) {
                            System.out.println("验签正确");
                            System.out.println(URLDecoder.decode(returnOriDKPayxml, InputCharset));
                            return "OK";
                        }
                    }
                } catch (UnsupportedEncodingException var12) {
                    System.out.println("解析密文报文有误:" + var12.getMessage());
                }
            }
        } else {
            System.out.println(tradeRequestXml.getErrMsg());
        }

        return "NO";
    }
}
